package com.cloud.form.common.driver;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;

import com.google.common.base.CaseFormat;

public class SimpleUpdateLangDriver extends XMLLanguageDriver {
	private static final Pattern pattern = Pattern.compile("\\(#\\{(\\w+)\\}\\)");

	@Override
	public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {
		Matcher matcher = pattern.matcher(script);
		if (matcher.find()) {
			StringBuilder sql = new StringBuilder();
			sql.append("<set>");
			for (Field field : parameterType.getDeclaredFields()) {
				String tmp = "<if test=\"_field != null\">_column=#{_field},</if>";
				sql.append(tmp.replaceAll("_field", field.getName()).replaceAll("_column",
						CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName())));
			}
			sql.append("</set>");
			sql.deleteCharAt(sql.lastIndexOf(","));
			script = matcher.replaceAll(sql.toString());
		}
		script = "<script>" + script + "</script>";
		return super.createSqlSource(configuration, script, parameterType);

	}

}
